import {MEMBER} from '../type';
import config from '../../config';

import axios from 'axios';
import Tips from 'react-native-root-tips';
import {DeviceEventEmitter,ToastAndroid } from 'react-native';


const instance = axios.create({
    baseURL: config.BASEURL,
    headers: {'Content-Type': 'multipart/form-data'}
});
// 获取会员列表
const getUserList = (page,text,type, callback) => async (dispatch, getState) => {
    console.log(text);
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/getUsersByCredentials', {
        params: {
            keyword: text,
            page:page,
            type: type
        },
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data && res.data.length) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let isLoadMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['member']['userList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: MEMBER.USER_LIST,
                    res: list
                })
                DeviceEventEmitter.emit('isLoadMore',isLoadMore);
            } else {
                dispatch({
                    type: MEMBER.USER_LIST,
                    res: []
                })
                ToastAndroid.showWithGravity('未搜索到会员', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    console.log(res);
    callback && callback(res);
};
//上传单张图片
const uploadImage = (file, callback) =>async (dispatch,getState) =>{
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});



    const res = await instance.post('api/v2/shop/image/upload', file, {
        Accept: 'Application/json',
        'Content-Type': 'multipart/form-data',
    }).then(res => {
        console.log(666);
        Tips.hide();
        if(res.status){
            if(res.data){
                dispatch({
                    type: MEMBER.AVATAR_FILE,
                    res: res.data
                })
            } else {
                ToastAndroid.showWithGravity('上传图片失败', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    },err =>{
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    })
    console.log(res);
    callback && callback(res);

}
//添加会员用户
const addUser = (info, callback) =>async (dispatch,getState) =>{
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.post('api/v2/shop/user/add', info, {
        headers: {
            Authorization: token
        }
    }).then(res => {
        Tips.hide();
        if(res.status){
            if(res.data){

            } else {
                ToastAndroid.showWithGravity('添加用户失败', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    },err =>{
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    })
    callback && callback(res);

}

// 获取会员优惠券列表
const getUserCouponList = (page,user_id, is_active = 1, limit, callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/user/coupon', {
        params: {
            page:page,
            user_id: user_id,
            is_active: is_active
        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                let list = [];
                let pages = res.meta.pagination;
                let current_page = pages.current_page;
                let total_pages = pages.total_pages;
                let hasMore = current_page < total_pages;
                if(page == 1){
                    list = res.data;
                } else {
                    let stateList = getState()['member']['couponList'];
                    list = stateList.concat(res.data);
                }
                dispatch({
                    type: MEMBER.COUPON_LIST,
                    res: list
                });
                DeviceEventEmitter.emit('hasMore',hasMore);
            } else {
                dispatch({
                    type: MEMBER.COUPON_LIST,
                    res: []
                });
            }
        } else {
            dispatch({
                type: MEMBER.COUPON_LIST,
                res: []
            });
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    console.log(res);
    callback && callback(res);
}

// 获取会员充值列表
const getUserBalanceList = (text, callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/balance/schemes', {
        params: {

        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: MEMBER.BALANCE_LIST,
                    res: res.data
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    console.log(res);
    callback && callback(res);
}

// 获取会员个人信息
const getUserDetail = (user_id,callback) => async (dispatch, getState) => {
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/user/detail/'+user_id, {
        params: {

        }
    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: MEMBER.USER_DETAIL,
                    res: res.data
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });

    console.log(res);
    callback && callback(res);
}


export default {
    getUserList,
    getUserCouponList,
    uploadImage,
    addUser,
    getUserBalanceList,
    getUserDetail
}